﻿using Dapper;
using System.Data.SqlClient;
using yunbo.Model.BIQI;

namespace yunbo.Repositorys.BIQIRepositorys
{
	public class QMS_ZJQXRepository
	{
		public string data = "Data Source=121.37.93.71;Initial Catalog=FanXingMES;User Id=sa;Password=geili@2025;TrustServerCertificate=true;";


		/// <summary>
		/// 获取质检缺陷
		/// </summary>
		/// <param name="state"></param>
		/// <param name="str"></param>
		/// <returns></returns>
		public List<QMS_ZJQX> GetQMS_ZJQX(int state, string? str)
		{
			List<QMS_ZJQX> zjqx = new List<QMS_ZJQX>();

			using (SqlConnection connection = new SqlConnection(data))
			{
				string sql = @"SELECT zjqx_id,zjqx_code, zjqx_name,(SELECT dictionary_name FROM dictionary WHERE dictionary_id = zjqx_fl) AS zjqx_fl_name,
    zjqx_fl,zjqx_remark,STUFF((SELECT ', ' + d.dictionary_name FROM STRING_SPLIT(zjqx_cpfl, ',') AS cpfl_code
            JOIN dictionary d ON LTRIM(RTRIM(cpfl_code.value)) = d.dictionary_code FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS zjqx_cpfl_name,
    zjqx_cpfl, zjqx_state FROM  [dbo].[qms_zjqx] 
WHERE [zjqx_isdelete] = 1 and [zjqx_state]=@state";
				if (str != null)
				{
					sql += @" and ([zjqx_code] like @str or [zjqx_name] like @str) ";
				}

				connection.Open();

				using (SqlCommand command = new SqlCommand(sql, connection))
				{
					command.Parameters.AddWithValue("@state", state);
					if (str != null)
					{
						command.Parameters.AddWithValue("@str", $"%{str}%");
					}

					using (SqlDataReader reader = command.ExecuteReader())
					{
						while (reader.Read())
						{
							zjqx.Add(new QMS_ZJQX
							{
								zjqx_id = Convert.ToInt32(reader["zjqx_id"]),
								zjqx_code = reader["zjqx_code"].ToString(),
								zjqx_name = reader["zjqx_name"].ToString(),
								zjqx_fl = Convert.ToInt32(reader["zjqx_fl"]),
								zjqx_fl_name = reader["zjqx_fl_name"].ToString(),
								zjqx_cpfl = reader["zjqx_cpfl"].ToString(),
								zjqx_cpfl_name = reader["zjqx_cpfl_name"].ToString(),
								zjqx_remark = reader["zjqx_remark"].ToString(),
								zjqx_state = Convert.ToInt32(reader["zjqx_state"])
							});
						}
					}
				}
			}
			return zjqx;
		}


		/// <summary>
		/// 改变状态
		/// </summary>
		/// <param name="id"></param>
		/// <param name="state"></param>
		/// <returns></returns>
		public bool StateChange(int id, int state)
		{
			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					string sql = @"update [dbo].[qms_zjqx] set [zjqx_state]=@State where [zjqx_id]=@Id";
					return connection.Execute(sql, new { Id = id, State = state }) > 0;
				}
			}
			catch (Exception ex)
			{
				// 记录日志等异常处理
				Console.WriteLine($"状态更改失败: {ex.Message}");
				return false;
			}
		}


		/// <summary>
		/// 新增
		/// </summary>
		/// <param name="zjqx"></param>
		/// <returns></returns>
		public bool AddQMS_ZJQX(QMS_ZJQX zjqx)
		{
			string sql = @"insert into [dbo].[qms_zjqx]
(zjqx_code, zjqx_name, zjqx_fl, zjqx_remark, zjqx_cpfl, zjqx_create_by)
values 
(@code,@name,@fl,@remark,@cpfl,1);";

			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					connection.Open();
					using (SqlCommand command = new SqlCommand(sql, connection))
					{
						command.Parameters.AddWithValue("@code", zjqx.zjqx_code);
						command.Parameters.AddWithValue("@name", zjqx.zjqx_name);
						command.Parameters.AddWithValue("@fl", zjqx.zjqx_fl);
						command.Parameters.AddWithValue("@remark", zjqx.zjqx_remark);
						command.Parameters.AddWithValue("@cpfl", zjqx.zjqx_cpfl);

						int rowsAffected = command.ExecuteNonQuery();
						return rowsAffected > 0; // 如果插入成功，返回 true
					}
				}
			}
			catch (Exception ex)
			{
				// 记录日志或处理异常
				Console.WriteLine("An error occurred: " + ex.Message);
				return false; // 如果发生异常，返回 false
			}
		}


		/// <summary>
		/// 修改
		/// </summary>
		/// <param name="zjqx"></param>
		/// <returns></returns>
		public bool UpdateQMS_ZJQX(QMS_ZJQX zjqx)
		{
			string sql = @"update [dbo].[qms_zjqx] set
zjqx_name=@name, zjqx_fl=@fl, zjqx_remark=@remark, zjqx_cpfl=@cpfl,
[zjqx_update_by]=1,[zjqx_update_time]=GETDATE()
where [zjqx_id]=@id";

			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					connection.Open();
					using (SqlCommand command = new SqlCommand(sql, connection))
					{
						command.Parameters.AddWithValue("@name", zjqx.zjqx_name);
						command.Parameters.AddWithValue("@fl", zjqx.zjqx_fl);
						command.Parameters.AddWithValue("@remark", zjqx.zjqx_remark);
						command.Parameters.AddWithValue("@cpfl", zjqx.zjqx_cpfl);
						command.Parameters.AddWithValue("@id", zjqx.zjqx_id);

						int rowsAffected = command.ExecuteNonQuery();
						return rowsAffected > 0; // 如果插入成功，返回 true
					}
				}
			}
			catch (Exception ex)
			{
				// 记录日志或处理异常
				Console.WriteLine("An error occurred: " + ex.Message);
				return false; // 如果发生异常，返回 false
			}
		}


		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public bool DelQMS_ZJQX(int id)
		{
			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					string sql = @"UPDATE [dbo].[qms_zjqx] 
                       SET zjqx_isdelete = 0 
                       WHERE zjqx_id = @Id";

					return connection.Execute(sql, new { Id = id }) > 0;
				}
			}
			catch (Exception ex)
			{
				// 记录日志等异常处理
				Console.WriteLine($"删除失败: {ex.Message}");
				return false;
			}
		}


		/// <summary>
		/// 批量删除
		/// </summary>
		/// <param name="ids"></param>
		/// <returns></returns>
		public bool DelQMS_ZJQXs(int[] ids)
		{
			// 参数验证
			if (ids == null || ids.Length == 0)
				return false;

			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					connection.Open();
					using (var transaction = connection.BeginTransaction()) // 添加事务
					{
						try
						{
							string sql = @"UPDATE [dbo].[qms_zjqx] 
		                                 SET zjqx_isdelete = 0 
		                                 WHERE zjqx_id IN @Ids";

							int affectedRows = connection.Execute(sql, new { Ids = ids }, transaction);
							transaction.Commit(); // 提交事务

							// 确保所有ID都成功更新
							return affectedRows == ids.Length;
						}
						catch
						{
							transaction.Rollback(); // 回滚事务
							throw;
						}
					}
				}
			}
			catch (Exception ex)
			{
				// 记录日志等异常处理
				Console.WriteLine($"批量删除失败: {ex.Message}");
				return false;
			}
		}
	}
}
